package controller

import (
	"strconv"

	"system-admin/config/boot"
	"system-admin/config/mysql"
	"system-admin/internal/app/web/service/user"
	"system-admin/internal/models"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type User struct{}
type UserOptionType struct {
	ID       string `json:"id"`
	Username string `json:"username"`
}

// All 所有用户
func (User) All(c *gin.Context) {
	list, total := user.AllUser(c.GetString("merchant_id"))
	response.JSON(c, map[string]interface{}{
		"list":  list,
		"total": total,
	}, nil)
}

// List 用户列表
func (User) List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	list, total := user.UserList(c.GetString("merchant_id"), page, limit)
	response.JSON(c, gin.H{
		"list":  list,
		"total": total,
	}, nil)
}

// UserDetail 用户详情
func (User) UserDetail(c *gin.Context) {
	response.JSON(c, user.UserDetail(c.GetString("user_id")), nil)
}

// Add 新增用户
func (User) Add(c *gin.Context) {
	var params struct {
		RoleID   string `json:"role_id"`
		Username string `json:"username"`
		Password string `json:"password"`
		Email    string `json:"email"`
	}
	c.ShouldBindWith(&params, binding.JSON)
	userID, err := user.AddUser(c.GetString("user_id"), params.RoleID, params.Username, params.Password, params.Email, 0)
	if err != nil {
		response.JSON(c, gin.H{
			"user_id": "",
		}, err)
	} else {
		response.JSON(c, gin.H{
			"user_id": userID,
		}, err)
	}
}

// Edit 编辑用户
func (User) Edit(c *gin.Context) {
	var params struct {
		UserID   string `json:"user_id"`
		RoleID   string `json:"role_id"`
		Password string `json:"password"`
		Email    string `json:"email"`
	}
	c.ShouldBindWith(&params, binding.JSON)
	err := user.EditUser(c.GetString("user_id"), params.UserID, params.RoleID, params.Password, params.Email, 0)
	response.JSON(c, nil, err)
}

// Delete 删除用户
func (User) Delete(c *gin.Context) {
	var params struct {
		UserID string `json:"user_id"`
	}
	c.ShouldBindWith(&params, binding.JSON)
	err := user.DeleteUser(c.GetString("user_id"), params.UserID)
	response.JSON(c, nil, err)
}

// Disable 禁用用户
func (User) Disable(c *gin.Context) {
	var params struct {
		UserID string `json:"user_id"`
	}
	c.ShouldBindWith(&params, binding.JSON)
	err := user.DisableUser(c.GetString("user_id"), params.UserID)
	response.JSON(c, nil, err)
}

// logout 退出
func (User) Logout(c *gin.Context) {
	err := user.Logout(c.GetHeader("Authorization"))
	response.JSON(c, nil, err)
}

func (User) ModifyPassword(c *gin.Context) {
	var params struct {
		Password        string `json:"old_password"`
		NewPassword     string `json:"new_password"`
		ConfirmPassword string `json:"confirm_password"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	err := user.ModifyPassword(c.GetString("user_id"), params.Password, params.NewPassword, params.ConfirmPassword)
	response.JSON(c, nil, err)
}

// LoginTokenCheck 登录token验证
func (User) LoginTokenCheck(c *gin.Context) {
	response.JSON(c, nil, nil)
}

// GetUserWechatOpenID 获取用户微信的openID
func (User) GetUserWechatOpenID(c *gin.Context) {
	code := c.Query("code")
	authorization := c.Query("Authorization")
	if authorization == "" {
		response.JSON(c, nil, errorx.New("缺少Authorization", -1))
		return
	}
	// 如果code为空，引导微信跳转以获取code
	if code == "" {
		redirect_uri := "http://" + c.Request.Host + c.Request.RequestURI
		boot.OfficialAccount.GetOauth().Redirect(
			c.Writer, c.Request,
			redirect_uri,
			"snsapi_base",
			authorization,
		)
	} else {
		//  获取并保存用户的微信id
		res, err := boot.OfficialAccount.GetOauth().GetUserAccessToken(code)
		if err == nil {
			openID := res.OpenID
			err := mysql.NewDB().Model(&models.User{}).
				Select("wechat_openid").
				Where("id = ?", c.GetString("user_id")).
				Update("wechat_openid", openID).Error
			if err != nil {
				response.JSON(c, nil, errorx.New("订阅告警消息失败"))
				return
			}
			response.JSON(c, nil, errorx.New("订阅告警消息成功", 0))
		}
	}
}
